package me.zhengjie.auth.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 描述该类- JPA
 *
 * @author zhoufei
 * @class: AuthorizationServer
 * @date 2020/10/28 21:26
 * @Verson 1.0 -2020/10/28 21:26
 * @see
 */

@Configuration
@EnableAuthorizationServer // 配置授权服务。
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    // 令牌存储策略
    private TokenStore tokenStore;
    @Autowired
    // 客户端详情服务,也就是configure(ClientDetailsServiceConfigurer clients)方法
    private ClientDetailsService clientDetailsService;

    @Autowired
    // 授权码服务
    private AuthorizationCodeServices authorizationCodeServices;
    @Autowired
    // 认证管理
    private AuthenticationManager authenticationManager;
    @Autowired
    // 令牌管理服务
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    // 用来配置客户端详情服务
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 这里是第三方合作用户的客户id，秘钥的配置
        // 使用in-memory存储
        clients.inMemory()
                // client_id，用户账号
                .withClient("nobug")
                // 客户端密钥
                .secret(new BCryptPasswordEncoder().encode("givemefive"))
                // 资源列表，资源标识
                .resourceIds("res1")
                // 授权类型（4种）
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit",
                        "refresh_token")
                // 客戶端允许的授权范围
                .scopes("all")
                // false跳转到授权页面，让用户点击授权，如果是true,相当于自动点击授权，就不跳转授权页面
                .autoApprove(false)//
                // 加上验证回调地址，返回授权码信息
                .redirectUris("http://www.baidu.com");

        // 如果有多个用户，配置多个客户详情
        // .and().withClient()

    }

    @Override
    // 用来配置令牌（token）的访问端点
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                // 密码模式需要
                .authenticationManager(authenticationManager)
                // 授权码模式需要
                .authorizationCodeServices(authorizationCodeServices)
                // 令牌管理服务
                .tokenServices(authorizationServerTokenServices)
//                .tokenServices(this.tokenService())
                .tokenStore(tokenStore)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);// 允许post提交
    }

    @Override
    // 用来配置令牌端点的安全约束,拦截规则
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

        security
                // 提供公有密匙的端点，如果你使用JWT令牌的话, 允许
                .tokenKeyAccess("permitAll()")
                // oauth/check_token：用于资源服务访问的令牌解析端点，允许
                .checkTokenAccess("permitAll()")
                // 表单认证,申请令牌
                .allowFormAuthenticationForClients();
    }

    @Bean
    // 授权码服务器
    public AuthorizationCodeServices authorizationCodeServices() {
        // 授权码模式的授权码采用内存方式存储
        return new InMemoryAuthorizationCodeServices();
    }

    @Bean
    // 令牌存储策略
    public TokenStore tokenStore() {
//        // 内存存储,普通令牌
//        return new InMemoryTokenStore();
        // 存入redis中
        return new MyRedisTokenStore(redisConnectionFactory);
    }

    // 令牌管理服务
//    @Bean
//    public AuthorizationServerTokenServices tokenService() {
//        DefaultTokenServices service = new DefaultTokenServices();
//        service.setClientDetailsService(clientDetailsService);
//        service.setSupportRefreshToken(true);// 支持刷新
//        service.setTokenStore(tokenStore);// 令牌存储
//        service.setAccessTokenValiditySeconds(7200); // 令牌默认有效期2小时
//        service.setRefreshTokenValiditySeconds(259200); // 刷新令牌默认有效期3天
//        return service;
//    }

    @Bean
    public RestTemplate restTemplate( ) {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(150000);//单位为ms
        factory.setConnectTimeout(50000);//单位为ms

        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode() !=401) {//根据错误类型需要修改
                    super.handleError(response);
                }
            }
        });

        return restTemplate;
    }

}

